package com.example.netty.biov1;

import com.example.netty.bio.ServerHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@Slf4j
public class Server {
    private static    int DEFLUT_PORT = 8888;
     // 单例
    private  static ServerSocket serverSocket;

    public static  void start( ) throws IOException{
        start(DEFLUT_PORT);
    }

    private synchronized static void start(int port) throws IOException {
       if(serverSocket !=null)return;
       try {
           serverSocket = new ServerSocket(port);
  //         System.out.println("服务端已启动，端口号为"+port);
           System.out.println("欢迎进入聊天系统 我是ai miss");
           while(true){
               //接收client 连接
               Socket socket = serverSocket.accept();

               new Thread(new ServerHandler(socket)).start();
           }
        }catch (IOException e){
           e.printStackTrace();
           System.out.println("服务端 启动异常，端口号为"+port);
       }finally {
               if (serverSocket !=null){
                   System.out.println("服务端 已关闭，端口号为"+port);
                   serverSocket.close();
                   serverSocket= null;
               }
       }


    }



}
